package com.campus.customer.service;

import com.campus.common.message.NewOrderMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class KafkaProducerService {

    private static final String NEW_ORDER_TOPIC = "new-order-topic";

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    
    @Resource
    private ObjectMapper objectMapper;

    public void sendNewOrderMessage(String orderId, Integer merchantId) {
        try {
            NewOrderMessage message = new NewOrderMessage(orderId, merchantId, System.currentTimeMillis());
            String messageJson = objectMapper.writeValueAsString(message);
            kafkaTemplate.send(NEW_ORDER_TOPIC, messageJson);
            log.info("新订单消息发送成功，订单ID: {}, 商户ID: {}", orderId, merchantId);
        } catch (Exception e) {
            log.error("发送新订单消息失败，订单ID: {}, 商户ID: {}", orderId, merchantId, e);
        }
    }
}